#include "ColorPickerDialog.h"
#include "ui_ColorPickerDialog.h"
#include "factories.h"

ColorPickerDialog::ColorPickerDialog(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::ColorPickerDialog)
{
    m_ui->setupUi(this);
	colorDialog = new QColorDialog(this);
	colorDialog->setOptions(colorDialog->options() | QColorDialog::ShowAlphaChannel);
	connect(colorDialog, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(selectedColorChanged(const QColor&)));
	
	m_ui->categoryComboBox->insertItems(0, QStringList(ColorFactory::instance().getCategories()));
	m_ui->colorKeyComboBox->insertItems(0, QStringList(ColorFactory::instance().getColorKeys(m_ui->categoryComboBox->currentText())));
}

ColorPickerDialog::~ColorPickerDialog()
{
    delete m_ui;
}

void ColorPickerDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ColorPickerDialog::show()
{
	int count = m_ui->categoryComboBox->count();
	m_ui->categoryComboBox->insertItems(count, QStringList(ColorFactory::instance().getCategories()));
	m_ui->categoryComboBox->setCurrentIndex(count);
	while (count--)
		m_ui->categoryComboBox->removeItem(0);
	
	QDialog::show();
}

void ColorPickerDialog::pickColor()
{
	colorDialog->show();
}

void ColorPickerDialog::resetColors()
{
	ColorFactory::instance().setDefaultColors();
	selectColorKey(m_ui->colorKeyComboBox->currentText());
	emit colorsChanged();
}
										
void ColorPickerDialog::loadColors()
{
	ColorFactory::instance().loadColorProfile();
	emit colorsChanged();
}

void ColorPickerDialog::saveColors()
{
	ColorFactory::instance().saveColorProfile();
}

void ColorPickerDialog::selectCategory(QString category)
{
	int count = m_ui->colorKeyComboBox->count();
	m_ui->colorKeyComboBox->insertItems(count, QStringList(ColorFactory::instance().getColorKeys(m_ui->categoryComboBox->currentText())));
	m_ui->colorKeyComboBox->setCurrentIndex(count);
	while (count--)
		   m_ui->colorKeyComboBox->removeItem(0);
}

void ColorPickerDialog::selectColorKey(QString key)
{
	Color4b color;
	QString selectedCategory = m_ui->categoryComboBox->currentText();
	ColorFactory::instance().getColor(color, selectedCategory, key);
	colorDialog->setCurrentColor(QColor(color[0], color[1], color[2], color[3]));
}

void ColorPickerDialog::selectedColorChanged(const QColor& selectedColor)
{
	QString selectedCategory = m_ui->categoryComboBox->currentText();
	QString selectedColorKey = m_ui->colorKeyComboBox->currentText();
	Color4b color = { selectedColor.red(), selectedColor.green(), selectedColor.blue(), selectedColor.alpha() };
	ColorFactory::instance().setColor(color, selectedCategory, selectedColorKey);
	emit colorsChanged();
}
